package com.xj.community.controller;

import com.xj.community.Service.DiscussPostService;
import com.xj.community.Service.LikeService;
import com.xj.community.Service.UserService;
import com.xj.community.entity.DiscussPost;
import com.xj.community.entity.Page;
import com.xj.community.entity.User;
import com.xj.community.util.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class HomeController implements CommunityConstant {
    @Autowired
    private UserService userService;
    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private LikeService likeService;

    @RequestMapping(path="/index",method = RequestMethod.GET)
    public String homePage(Model model, Page page){//返回主页视图层
        page.setLimit(6);
        page.setPath("/index");
        page.setRows(discussPostService.selectAllDiscussPost(0));
        List<DiscussPost> list = discussPostService.discussPostList(0, page.getOffset(), page.getLimit());
        //根据查询到的每一条帖子中的userId查找对应的用户并封装到对应的集合中
        List<Map<String,Object>> discussPosts = new ArrayList<>();
        if (list != null){
            for (DiscussPost discussPost : list) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("post",discussPost);
                map.put("user",userService.selectById(discussPost.getUserId()));
                long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, discussPost.getId());
                map.put("likeCount", likeCount);
                discussPosts.add(map);
            }
        }

        model.addAttribute("discussPosts",discussPosts);
        return "/index";
    }

    @RequestMapping(path = "/error", method = RequestMethod.GET)
    public String getErrorPage() {
        return "/error/500";
    }
}
